package com.zhiyu.controller;

import com.zhiyu.common.ApiReturn;
import com.zhiyu.pojo.Address;
import com.zhiyu.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequestMapping("address")
@Controller
@CrossOrigin
public class AddressController {

    @Autowired
    private AddressService addressService;
    
    //删除地址
    @RequestMapping("deleteAddress")
    @ResponseBody
    public ApiReturn deleteAddress(Address address){
        int count = addressService.delete(address);
        if (count<1){
            return ApiReturn.error("删除失败");
        }
        return ApiReturn.success("删除成功");
    }
    

    //修改地址
    @RequestMapping("updateAddress")
    @ResponseBody
    public ApiReturn updateAddress(Address Address){
        int count = addressService.update(Address);
        if (count<1){
            return ApiReturn.error("修改失败");
        }
        return ApiReturn.success("修改成功");
    }

    //添加地址
    @RequestMapping("addAddress")
    @ResponseBody
    public ApiReturn addAddress(Address address, HttpServletRequest request, HttpServletResponse response){
        address.setStatus(3);
        String userInfo = (String) request.getSession().getAttribute("userInfo");
        String[] userStr = userInfo.split(":");
        addressService.updateDefaultStatus(Integer.valueOf(userStr[0]));
        int count = addressService.insert(address);
        if (count<1){
            return ApiReturn.error("添加失败");
        }
        return ApiReturn.success("添加成功");
    }

    //判断用户是否有默认地址
    @RequestMapping("isDefaultAddress")
    @ResponseBody
    public ApiReturn isDefaultAddress(HttpServletRequest request, HttpServletResponse response){
        String userInfo = (String) request.getSession().getAttribute("userInfo");
        String[] userStr = userInfo.split(":");
        Address address = addressService.selectDefault(Integer.valueOf(userStr[0]));
        if (address == null ){
            return ApiReturn.error("用户没用默认地址");
        }
        return ApiReturn.success("可以支付");
    }


}
